import React, { useState, useRef, useEffect, useCallback } from 'react';
import styles from './zhibo.module.css';

// 聊天发送端组件
const ChatSender = ({ roomId = 'chat-room-001' }) => {
  const [messages, setMessages] = useState([]);
  const [inputMessage, setInputMessage] = useState('');
  const [isConnected, setIsConnected] = useState(false);
  const [error, setError] = useState(null);
  const [username, setUsername] = useState('讲师');
  const [isStreaming, setIsStreaming] = useState(false);
  const [viewerCount, setViewerCount] = useState(0);
  const [rtcConnected, setRtcConnected] = useState(false);
  const [showEmojiPicker, setShowEmojiPicker] = useState(false);
  const [showPlusMenu, setShowPlusMenu] = useState(false);
  const [showSendButton, setShowSendButton] = useState(false);
  // 语音录制相关状态
  const [isRecording, setIsRecording] = useState(false);
  const [recordingTime, setRecordingTime] = useState(0);
  const [mediaRecorder, setMediaRecorder] = useState(null);
  const [audioChunks, setAudioChunks] = useState([]);

  const wsRef = useRef(null);
  const messagesEndRef = useRef(null);
  const localVideoRef = useRef(null);
  const peerConnectionRef = useRef(null);
  const dataChannelRef = useRef(null);
  const localStreamRef = useRef(null);
  const recordingTimerRef = useRef(null);

  // 自动滚动到底部
  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  };

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  // 格式化录音时间
  const formatRecordingTime = (seconds) => {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  };

  // 开始录音
  const startRecording = async () => {
    try {
      // 检查浏览器是否支持录音
      if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
        setError('您的浏览器不支持录音功能');
        return;
      }

      // 检查是否支持MediaRecorder
      if (!window.MediaRecorder) {
        setError('您的浏览器不支持MediaRecorder API');
        return;
      }

      const stream = await navigator.mediaDevices.getUserMedia({ 
        audio: {
          echoCancellation: true,
          noiseSuppression: true,
          autoGainControl: true
        } 
      });
      
      // 检查支持的MIME类型
      const mimeType = MediaRecorder.isTypeSupported('audio/webm;codecs=opus') 
        ? 'audio/webm;codecs=opus' 
        : MediaRecorder.isTypeSupported('audio/webm') 
          ? 'audio/webm' 
          : 'audio/mp4';
      
      const recorder = new MediaRecorder(stream, {
        mimeType: mimeType
      });
      
      const chunks = [];
      
      recorder.ondataavailable = (event) => {
        if (event.data.size > 0) {
          chunks.push(event.data);
        }
      };
      
      recorder.onstop = () => {
        const audioBlob = new Blob(chunks, { type: 'audio/webm' });
        sendVoiceMessage(audioBlob);
        
        // 停止所有音轨
        stream.getTracks().forEach(track => track.stop());
      };
      
      recorder.start();
      setMediaRecorder(recorder);
      setAudioChunks(chunks);
      setIsRecording(true);
      setRecordingTime(0);
      
      // 开始计时
      recordingTimerRef.current = setInterval(() => {
        setRecordingTime(prev => {
          const newTime = prev + 1;
          // 限制录音时长为5分钟
          if (newTime >= 300) {
            stopRecording();
            setError('录音时长已达到5分钟限制');
            return prev;
          }
          return newTime;
        });
      }, 1000);
      
      console.log('开始录音');
    } catch (error) {
      console.error('录音失败:', error);
      setError('无法访问麦克风，请检查权限设置');
    }
  };

  // 停止录音
  const stopRecording = () => {
    if (mediaRecorder && mediaRecorder.state === 'recording') {
      mediaRecorder.stop();
      setIsRecording(false);
      
      // 清除计时器
      if (recordingTimerRef.current) {
        clearInterval(recordingTimerRef.current);
        recordingTimerRef.current = null;
      }
      
      console.log('停止录音');
    }
  };

  // 发送语音消息
  const sendVoiceMessage = (audioBlob) => {
    if (!username.trim()) {
      setError('请输入用户名');
      return;
    }

    // 检查录音时长是否太短
    if (recordingTime < 1) {
      setError('录音时间太短，请重新录音');
      return;
    }

    // 检查音频文件大小
    if (audioBlob.size > 10 * 1024 * 1024) { // 10MB限制
      setError('录音文件过大，请缩短录音时间');
      return;
    }

    // 创建音频URL用于播放
    const audioUrl = URL.createObjectURL(audioBlob);
    
    const messageData = {
      content: `🎤 语音消息 (${formatRecordingTime(recordingTime)})`,
      sender: username,
      timestamp: new Date().toISOString(),
      type: 'voice',
      audioUrl: audioUrl,
      duration: recordingTime
    };

    // 优先使用WebRTC数据通道发送
    console.log('主播端检查数据通道状态:', {
      dataChannelExists: !!dataChannelRef.current,
      readyState: dataChannelRef.current?.readyState,
      rtcConnected: rtcConnected
    });
    
    // 检查数据通道是否可用
    if (dataChannelRef.current && dataChannelRef.current.readyState === 'open' && rtcConnected) {
      try {
        // 将音频数据转换为base64
        const reader = new FileReader();
        reader.onload = () => {
          const base64Audio = reader.result;
          const messageToSend = {
            type: 'voice-message',
            data: {
              ...messageData,
              audioData: base64Audio
            }
          };
          
          console.log('📤 主播端通过数据通道发送语音消息');
          console.log('消息内容:', messageToSend);
          console.log('数据通道状态:', dataChannelRef.current.readyState);
          dataChannelRef.current.send(JSON.stringify(messageToSend));
          console.log('✅ 语音消息已发送');
          
          // 添加到本地消息列表
          setMessages(prev => [...prev, {
            id: Date.now() + Math.random(),
            ...messageData
          }]);
          
          setError(null);
        };
        reader.readAsDataURL(audioBlob);
        return;
      } catch (error) {
        console.error('WebRTC数据通道发送语音失败:', error);
      }
    }
    
    // 回退到WebSocket
    if (wsRef.current?.readyState === WebSocket.OPEN) {
      console.log('主播端回退到WebSocket发送语音消息');
      
      // 将音频数据转换为base64
      const reader = new FileReader();
      reader.onload = () => {
        const base64Audio = reader.result;
        const wsMessageData = {
          type: 'voice-message',
          data: {
            message: `🎤 语音消息 (${formatRecordingTime(recordingTime)})`,
            userId: username,
            timestamp: new Date().toISOString(),
            audioData: base64Audio,
            duration: recordingTime
          },
          roomId
        };

        wsRef.current.send(JSON.stringify(wsMessageData));
        
        // 添加到本地消息列表
        setMessages(prev => [...prev, {
          id: Date.now() + Math.random(),
          ...messageData
        }]);
        
        setError(null);
      };
      reader.readAsDataURL(audioBlob);
    } else {
      setError('连接已断开，请等待重连');
    }
  };

  // 切换录音状态
  const toggleRecording = () => {
    if (isRecording) {
      stopRecording();
    } else {
      startRecording();
    }
  };

  // 播放语音消息
  const playVoiceMessage = (audioUrl) => {
    const audio = new Audio(audioUrl);
    
    // 添加播放状态
    const voiceMessage = document.querySelector(`[data-audio-url="${audioUrl}"]`);
    if (voiceMessage) {
      voiceMessage.classList.add(styles.playing);
    }
    
    audio.play().then(() => {
      // 播放成功后移除加载状态，添加播放状态
      if (voiceMessage) {
        voiceMessage.classList.remove(styles.loading, styles.error);
        voiceMessage.classList.add(styles.playing);
      }
    }).catch(error => {
      console.error('播放语音失败:', error);
      setError('播放语音失败');
      // 播放失败时移除加载状态，添加错误状态
      if (voiceMessage) {
        voiceMessage.classList.remove(styles.loading);
        voiceMessage.classList.add(styles.error);
      }
    });
    
    // 播放结束后移除播放状态
    audio.onended = () => {
      if (voiceMessage) {
        voiceMessage.classList.remove(styles.playing);
      }
    };
    
    // 播放出错时也移除播放状态
    audio.onerror = () => {
      if (voiceMessage) {
        voiceMessage.classList.remove(styles.playing, styles.loading);
        voiceMessage.classList.add(styles.error);
      }
    };
  };

  // WebSocket连接
  const connectWebSocket = useCallback(() => {
    if (wsRef.current?.readyState === WebSocket.OPEN) return;
    
    try {
      console.log('聊天端: 连接WebSocket服务器...');
      const wsUrl = `ws://${window.location.hostname}:9001/room/${roomId}`;
      console.log('连接URL:', wsUrl);
      const ws = new WebSocket(wsUrl);
      
      ws.onopen = () => {
        console.log('聊天端WebSocket连接成功');
        setIsConnected(true);
        setError(null);
        
        // 自动加入聊天室
        setTimeout(() => {
          if (ws.readyState === WebSocket.OPEN) {
            console.log('主播端发送user-join消息');
            ws.send(JSON.stringify({
              type: 'user-join',
              roomId
            }));
          }
        }, 100);
      };
      
      ws.onmessage = (event) => {
        try {
          const message = JSON.parse(event.data);
          console.log('收到消息:', message.type);
          handleMessage(message);
        } catch (error) {
          console.error('处理消息失败:', error);
        }
      };
      
      ws.onclose = () => {
        console.log('聊天端WebSocket连接关闭');
        setIsConnected(false);
        // 自动重连
        setTimeout(connectWebSocket, 3000);
      };
      
      ws.onerror = (error) => {
        console.error('聊天端WebSocket错误:', error);
        setIsConnected(false);
        setError('连接失败，正在重试...');
      };
      
      wsRef.current = ws;
    } catch (error) {
      console.error('WebSocket连接失败:', error);
      setError(`连接失败: ${error.message}`);
      setTimeout(connectWebSocket, 5000);
    }
  }, [roomId]);

  // 处理收到的消息
  const handleMessage = (message) => {
    const { type, data, from } = message;
    
    console.log('主播端收到消息详情:', { type, data, from });
    
    switch (type) {
      case 'chat-message':
        if (data && data.userId !== username) {
          setMessages(prev => [...prev, {
            id: Date.now() + Math.random(),
            content: data.message,
            sender: data.userId,
            timestamp: data.timestamp,
            type: 'received'
          }]);
        }
        break;
      case 'voice-message':
        if (data && data.userId !== username) {
          // 将base64音频数据转换为Blob
          const audioBlob = dataURLToBlob(data.audioData);
          const audioUrl = URL.createObjectURL(audioBlob);
          
          setMessages(prev => [...prev, {
            id: Date.now() + Math.random(),
            content: `🎤 语音消息 (${formatRecordingTime(data.duration || 0)})`,
            sender: data.userId,
            timestamp: data.timestamp,
            type: 'voice',
            audioUrl: audioUrl,
            duration: data.duration
          }]);
        }
        break;
      case 'system-message':
        setMessages(prev => [...prev, {
          id: Date.now() + Math.random(),
          content: data.message,
          sender: '系统',
          timestamp: new Date().toISOString(),
          type: 'system'
        }]);
        break;
      case 'answer':
        console.log('主播端收到answer消息，开始处理...');
        console.log('收到观众端answer:', data.answer);
        if (peerConnectionRef.current && data.answer) {
          console.log('开始设置远程描述...');
          peerConnectionRef.current.setRemoteDescription(new RTCSessionDescription(data.answer))
            .then(() => {
              console.log('远程描述设置成功');
              console.log('WebRTC连接状态:', peerConnectionRef.current.connectionState);
              console.log('ICE连接状态:', peerConnectionRef.current.iceConnectionState);
              console.log('信令状态:', peerConnectionRef.current.signalingState);
            })
            .catch(error => console.error('设置远程描述失败:', error));
        } else {
          console.log('无法设置远程描述 - peerConnection或answer为空');
          console.log('peerConnectionRef.current:', peerConnectionRef.current);
          console.log('data.answer:', data.answer);
        }
        break;
      case 'ice-candidate':
        if (peerConnectionRef.current && data.candidate) {
          peerConnectionRef.current.addIceCandidate(new RTCIceCandidate(data.candidate))
            .catch(error => console.error('添加ICE候选失败:', error));
        }
        break;
      case 'error':
        setError(data?.message || '服务器错误');
        break;
      default:
        console.log('未知消息类型:', type);
    }
  };

  // 将dataURL转换为Blob
  const dataURLToBlob = (dataURL) => {
    const arr = dataURL.split(',');
    const mime = arr[0].match(/:(.*?);/)[1];
    const bstr = atob(arr[1]);
    let n = bstr.length;
    const u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
  };

  // 发送消息 - 优先使用WebRTC数据通道
  const sendMessage = () => {
    if (!inputMessage.trim() || !username.trim()) {
      setError('请输入用户名和消息内容');
      return;
    }
    
    const messageData = {
      content: inputMessage.trim(),
      sender: username,
      timestamp: new Date().toISOString(),
      type: 'sent'
    };

    // 优先使用WebRTC数据通道发送
    if (dataChannelRef.current && dataChannelRef.current.readyState === 'open') {
      try {
        const messageToSend = {
          type: 'chat-message',
          data: messageData
        };
        console.log('主播端通过数据通道发送消息:', messageToSend);
        dataChannelRef.current.send(JSON.stringify(messageToSend));
        
        // 添加到本地消息列表
        setMessages(prev => [...prev, {
          id: Date.now() + Math.random(),
          ...messageData
        }]);
        
        setInputMessage('');
        setError(null);
        return;
      } catch (error) {
        console.error('WebRTC数据通道发送失败:', error);
      }
    } else {
      console.log('主播端数据通道状态:', dataChannelRef.current?.readyState || '未创建');
      console.log('主播端数据通道引用:', dataChannelRef.current);
      console.log('主播端WebRTC连接状态:', rtcConnected);
    }
    
    // 回退到WebSocket
    if (wsRef.current?.readyState === WebSocket.OPEN) {
      console.log('主播端回退到WebSocket发送消息');
      const wsMessageData = {
        type: 'chat-message',
        data: {
          message: inputMessage.trim(),
          userId: username,
          timestamp: new Date().toISOString()
        },
        roomId
      };

      wsRef.current.send(JSON.stringify(wsMessageData));
      
      // 添加到本地消息列表
      setMessages(prev => [...prev, {
        id: Date.now() + Math.random(),
        content: inputMessage.trim(),
        sender: username,
        timestamp: new Date().toISOString(),
        type: 'sent'
      }]);
      
      setInputMessage('');
      setError(null);
    } else {
      setError('连接已断开，请等待重连');
    }
  };

  // 处理回车键发送
  const handleKeyPress = (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      sendMessage();
    }
  };

  // 添加表情到输入框
  const addEmoji = (emoji) => {
    setInputMessage(prev => prev + emoji);
    setShowEmojiPicker(false);
  };

  // 切换表情包选择器
  const toggleEmojiPicker = () => {
    setShowEmojiPicker(prev => !prev);
  };

  // 创建WebRTC连接
  const createPeerConnection = () => {
    const configuration = {
      iceServers: [
        { urls: 'stun:stun.l.google.com:19302' },
        { urls: 'stun:stun1.l.google.com:19302' }
      ]
    };

    const peerConnection = new RTCPeerConnection(configuration);
    
    // 创建数据通道用于聊天 - 统一使用'chat'通道名称
    const dataChannel = peerConnection.createDataChannel('chat', {
      ordered: true
    });
    
    console.log('主播端数据通道已创建:', dataChannel);
    console.log('数据通道初始状态:', dataChannel.readyState);
    
    // 立即设置数据通道引用
    dataChannelRef.current = dataChannel;
    
    dataChannel.onopen = () => {
      console.log('🎉 主播端数据通道已打开');
      console.log('数据通道打开时状态:', dataChannel.readyState);
      console.log('WebRTC连接状态:', peerConnection.connectionState);
      console.log('ICE连接状态:', peerConnection.iceConnectionState);
      setRtcConnected(true);
      console.log('✅ 主播端WebRTC连接已建立，可以发送消息');
    };
    
    dataChannel.onerror = (error) => {
      console.error('主播端数据通道错误:', error);
      setRtcConnected(false);
    };
    
    dataChannel.onconnecting = () => {
      console.log('主播端数据通道正在连接...');
    };
    
    dataChannel.onclose = () => {
      console.log('主播端数据通道已关闭');
      setRtcConnected(false);
      dataChannelRef.current = null;
    };
    
            dataChannel.onmessage = (event) => {
          try {
            const message = JSON.parse(event.data);
            console.log('主播端收到数据通道消息:', message);
            console.log('消息类型:', message.type);
            if (message.type === 'chat-message') {
              setMessages(prev => [...prev, {
                id: Date.now() + Math.random(),
                content: message.data.content,
                sender: message.data.sender,
                timestamp: message.data.timestamp,
                type: 'received'
              }]);
            } else if (message.type === 'voice-message') {
              // 将base64音频数据转换为Blob
              const audioBlob = dataURLToBlob(message.data.audioData);
              const audioUrl = URL.createObjectURL(audioBlob);
              
              setMessages(prev => [...prev, {
                id: Date.now() + Math.random(),
                content: `🎤 语音消息 (${formatRecordingTime(message.data.duration || 0)})`,
                sender: message.data.sender,
                timestamp: message.data.timestamp,
                type: 'voice',
                audioUrl: audioUrl,
                duration: message.data.duration
              }]);
            }
          } catch (error) {
            console.error('处理数据通道消息失败:', error);
          }
        };
    
    // 主播端创建数据通道，不需要处理接收到的数据通道
    // 移除ondatachannel处理逻辑，因为主播端是发起方
    
    // 监听连接状态变化
    peerConnection.onconnectionstatechange = () => {
      console.log('主播端WebRTC连接状态变化:', peerConnection.connectionState);
      if (peerConnection.connectionState === 'connected') {
        console.log('主播端WebRTC连接已建立');
        setRtcConnected(true);
      } else if (peerConnection.connectionState === 'disconnected' || 
                 peerConnection.connectionState === 'failed') {
        console.log('主播端WebRTC连接已断开');
        setRtcConnected(false);
      }
    };
    
    // ICE候选处理
    peerConnection.onicecandidate = (event) => {
      if (event.candidate && wsRef.current?.readyState === WebSocket.OPEN) {
        wsRef.current.send(JSON.stringify({
          type: 'ice-candidate',
          candidate: event.candidate,
          roomId
        }));
      }
    };
    
    peerConnectionRef.current = peerConnection;
    return peerConnection;
  };

  // 开始聊天（不使用摄像头和麦克风）
  const startStream = async () => {
    try {
      console.log('开始创建WebRTC连接...');
      
      // 先停止现有连接
      if (peerConnectionRef.current) {
        console.log('停止现有WebRTC连接...');
        peerConnectionRef.current.close();
        peerConnectionRef.current = null;
      }
      
      if (dataChannelRef.current) {
        console.log('关闭现有数据通道...');
        dataChannelRef.current.close();
        dataChannelRef.current = null;
      }
      
      // 重置连接状态
      setRtcConnected(false);
      
      // 创建WebRTC连接（仅用于数据通道）
      const peerConnection = createPeerConnection();
      console.log('WebRTC连接已创建:', peerConnection);
      
      // 等待数据通道状态变为connecting或open
      console.log('等待数据通道建立...');
      
      // 创建offer（仅数据通道，无媒体流）
      const offer = await peerConnection.createOffer();
      console.log('Offer已创建:', offer);
      
      await peerConnection.setLocalDescription(offer);
      console.log('本地描述已设置');
      
      // 通过WebSocket发送offer
      if (wsRef.current?.readyState === WebSocket.OPEN) {
        const offerMessage = {
          type: 'offer',
          offer: offer,
          roomId
        };
        console.log('准备发送offer消息:', offerMessage);
        wsRef.current.send(JSON.stringify(offerMessage));
        console.log('Offer已通过WebSocket发送');
      } else {
        console.error('WebSocket未连接，无法发送offer');
      }
      
      setIsStreaming(true);
      console.log('主播端开始聊天状态已设置');
      
      // 等待一段时间让数据通道建立
      setTimeout(() => {
        console.log('=== 主播端连接状态检查 ===');
        console.log('数据通道状态:', dataChannelRef.current?.readyState);
        console.log('数据通道引用:', !!dataChannelRef.current);
        console.log('WebRTC连接状态:', peerConnection.connectionState);
        console.log('ICE连接状态:', peerConnection.iceConnectionState);
        console.log('信令状态:', peerConnection.signalingState);
        console.log('RTC连接状态:', rtcConnected);
        console.log('WebSocket状态:', wsRef.current?.readyState);
        
        if (dataChannelRef.current && dataChannelRef.current.readyState === 'open') {
          console.log('✅ 数据通道已成功建立');
        } else {
          console.log('❌ 数据通道尚未建立，状态:', dataChannelRef.current?.readyState);
        }
        
        if (peerConnection.connectionState === 'connected') {
          console.log('✅ WebRTC连接已建立');
        } else {
          console.log('❌ WebRTC连接未建立，状态:', peerConnection.connectionState);
        }
        
        // 测试发送一条消息
        if (dataChannelRef.current && dataChannelRef.current.readyState === 'open') {
          console.log('🧪 测试发送一条消息...');
          const testMessage = {
            type: 'chat-message',
            data: {
              content: '测试消息',
              sender: '主播端',
              timestamp: new Date().toISOString()
            }
          };
          dataChannelRef.current.send(JSON.stringify(testMessage));
          console.log('✅ 测试消息已发送');
        }
        console.log('========================');
      }, 2000);
      
    } catch (error) {
      console.error('创建WebRTC连接失败:', error);
      setError('无法建立连接');
    }
  };

  // 停止聊天
  const stopStream = () => {
    // 关闭WebRTC连接
    if (peerConnectionRef.current) {
      peerConnectionRef.current.close();
      peerConnectionRef.current = null;
    }
    
    if (dataChannelRef.current) {
      dataChannelRef.current.close();
      dataChannelRef.current = null;
    }
    
    setIsStreaming(false);
    setRtcConnected(false);
  };

  // 组件加载时连接WebSocket并自动开始聊天
  useEffect(() => {
    connectWebSocket();
    
    // 延迟一段时间后自动开始聊天
    const timer = setTimeout(() => {
      if (isConnected) {
        console.log('自动开始聊天...');
        startStream();
      }
    }, 2000); // 等待2秒确保WebSocket连接稳定
    
    return () => {
      clearTimeout(timer);
      if (wsRef.current) {
        wsRef.current.close();
      }
      // 清理录音相关资源
      if (recordingTimerRef.current) {
        clearInterval(recordingTimerRef.current);
      }
      if (mediaRecorder && mediaRecorder.state === 'recording') {
        mediaRecorder.stop();
      }
    };
  }, []);

  // 返回首页函数
  const goToHome = () => {
    window.location.href = '/';
  };

  return (
    <div className={styles.container}>
      <div className={styles.chatHeader}>
        <button 
          className={styles.backButton} 
          onClick={goToHome}
          title="返回首页"
        >
          ←
        </button>
        <h2 className={styles.chatTitle}>讲师</h2>
      </div>
      
      <div className={styles.videoSection}>
        <div className={styles.videoPlaceholder}>
          
        </div>
      </div>

      <div className={styles.chatContainer}>
        <div className={styles.usernameSection}>
          <div className={styles.fixedUsername}>
            <span className={styles.usernameLabel}>用户名：</span>
            <span className={styles.usernameValue}>{username}</span>
          </div>
        </div>

        <div className={styles.messagesContainer}>
          {messages.length === 0 ? (
            <div className={styles.emptyState}>
              <p>💬 暂无消息</p>
              <p>开始聊天吧！</p>
            </div>
          ) : (
            messages.map((msg, index) => {
              const isOwnMessage = msg.sender === username;
              const isSystemMessage = msg.type === 'system';
              
              return (
                <div 
                  key={index} 
                  className={`${styles.messageItem} ${
                    isSystemMessage 
                      ? styles.system 
                      : isOwnMessage 
                        ? `${styles.sent} ${styles.ownMessage}` 
                        : styles.received
                  }`}
                >
                  {!isSystemMessage && (
                    <div className={styles.messageHeader}>
                      <span className={styles.sender}>{msg.sender}</span>
                      <span className={styles.timestamp}>
                        {new Date(msg.timestamp || Date.now()).toLocaleTimeString('zh-CN', {
                          hour: '2-digit',
                          minute: '2-digit'
                        })}
                      </span>
                    </div>
                  )}
                  <div className={styles.messageContent}>
                    {msg.type === 'voice' ? (
                      <div 
                        className={styles.voiceMessage}
                        data-audio-url={msg.audioUrl}
                        title={`点击播放${msg.duration}秒语音消息`}
                      >
                        <div className={styles.voiceMessageContent}>
                          <span className={styles.voiceDuration}>
                            {msg.duration ? `${msg.duration}"` : '0"'}
                          </span>
                          <div 
                            className={styles.voicePlayIcon}
                            onClick={() => playVoiceMessage(msg.audioUrl)}
                            role="button"
                            tabIndex={0}
                            aria-label={`播放${msg.duration}秒语音消息`}
                            onKeyDown={(e) => {
                              if (e.key === 'Enter' || e.key === ' ') {
                                e.preventDefault();
                                playVoiceMessage(msg.audioUrl);
                              }
                            }}
                          >
                            <div className={styles.voicePlayTriangle}></div>
                          </div>
                        </div>
                      </div>
                    ) : (
                      msg.content
                    )}
                  </div>
                </div>
              );
            })
          )}
        </div>

        <div className={styles.inputSection}>
          <div className={styles.inputContainer}>
            <button 
              className={`${styles.voiceButton} ${isRecording ? styles.recording : ''}`}
              onClick={toggleRecording}
              disabled={!isConnected}
            >
              <span className={styles.voiceIcon}>
                {isRecording ? '⏹️' : '🎤'}
              </span>
              {isRecording && (
                <span className={styles.recordingTime}>
                  {formatRecordingTime(recordingTime)}
                </span>
              )}
            </button>
            <textarea
              value={inputMessage}
              onChange={(e) => {
                setInputMessage(e.target.value);
                setShowSendButton(e.target.value.trim().length > 0);
              }}
              onFocus={() => {
                setShowSendButton(true);
                setShowEmojiPicker(false);
                setShowPlusMenu(false);
              }}
              onBlur={() => {
                if (inputMessage.trim().length === 0) {
                  setShowSendButton(false);
                }
              }}
              onKeyPress={(e) => {
                if (e.key === 'Enter' && !e.shiftKey) {
                  e.preventDefault();
                  sendMessage();
                }
              }}
              placeholder="输入消息... (Shift+Enter 换行)"
              disabled={!isConnected}
              className={styles.messageInput}
              rows={1}
            />
            {!showSendButton && (
              <>
                <button 
                  onClick={() => {
                    console.log('表情包按钮被点击');
                    toggleEmojiPicker();
                  }}
                  className={styles.emojiButton}
                  type="button"
                >
                  😊
                </button>
                <button 
                  onClick={() => setShowPlusMenu(!showPlusMenu)}
                  className={styles.plusButton}
                  type="button"
                >
                  +
                </button>
              </>
            )}
          </div>
          
          {/* 表情包选择器 */}
          {showEmojiPicker && (
            <div className={styles.emojiPicker}>
              <div className={styles.emojiGrid}>
                {['😀', '😃', '😄', '😁', '😆', '😅', '😂',
                 '🤣', '😊', '😇', '🙂', '🙃', '😉', '😌', 
                 '😍', '🥰', '😘', '😗', '😙', '😚', '😋', 
                 '😛', '😝', '😜', '🤪', '🤨', '🧐', '🤓', 
                 '😎', '🤩', '🥳', '😏', '😒', '😞', '😔', 
                 '😟', '😕', '🙁', '☹️', '😣', '😖', '😫', 
                 '😩', '🥺', '😢', '😭', '😤', '😠', '😡',
                  '🤬', '🤯', '😳', '🥵', '🥶', '😱', '😨', 
                  '😰', '😥', '😓', '🤗', '🤔', '🤭', '🤫', 
                  '🤥', '😶', '😐', '😑', '😯', '😦', '😧',
                   '😮', '😲', '🥱', '😴', '🤤', '😪', '😵', 
                   '🤐', '🥴', '🤢', '🤮', '🤧', '😷', '🤒', 
                   '🤕', '🤑', '🤠', '💩', '👻', '💀', '☠️',
                    '👽', '👾', '🤖', '😺', '😸', '😹', '😻', '😼', '😽'].map((emoji, index) => (
                  <button
                    key={index}
                    onClick={() => addEmoji(emoji)}
                    className={styles.emojiItem}
                    type="button"
                  >
                    {emoji}
                  </button>
                ))}
              </div>
            </div>
          )}

          {/* 加号菜单 */}
          {showPlusMenu && (
            <div className={styles.plusMenu}>
              <div className={styles.plusMenuGrid}>
                <button className={styles.plusMenuItem}>
                  <span className={styles.plusMenuIcon}>🖼️</span>
                  <span className={styles.plusMenuText}>相册</span>
                </button>
                <button className={styles.plusMenuItem}>
                  <span className={styles.plusMenuIcon}>📷</span>
                  <span className={styles.plusMenuText}>拍摄</span>
                </button>
                <button className={styles.plusMenuItem}>
                  <span className={styles.plusMenuIcon}>📍</span>
                  <span className={styles.plusMenuText}>位置</span>
                </button>
                <button className={styles.plusMenuItem}>
                  <span className={styles.plusMenuIcon}>🎤</span>
                  <span className={styles.plusMenuText}>语音输入</span>
                </button>
                <button className={styles.plusMenuItem}>
                  <span className={styles.plusMenuIcon}>📦</span>
                  <span className={styles.plusMenuText}>收藏</span>
                </button>
                <button className={styles.plusMenuItem}>
                  <span className={styles.plusMenuIcon}>👤</span>
                  <span className={styles.plusMenuText}>个人名片</span>
                </button>
                <button className={styles.plusMenuItem}>
                  <span className={styles.plusMenuIcon}>📁</span>
                  <span className={styles.plusMenuText}>文件</span>
                </button>
                <button className={styles.plusMenuItem}>
                  <span className={styles.plusMenuIcon}>🎵</span>
                  <span className={styles.plusMenuText}>音乐</span>
                </button>
              </div>
            </div>
          )}

          {/* 发送按钮 */}
          {showSendButton && (
            <div className={styles.sendButtonContainer}>
              <button 
                onClick={sendMessage}
                disabled={!isConnected || !inputMessage.trim()}
                className={styles.sendButton}
              >
                发送
              </button>
            </div>
          )}
          
          {!isConnected && (
            <div className={styles.inputTips}>
              请先输入用户名并等待连接
            </div>
          )}
        </div>
      </div>

  
    </div>
  );
};

export default ChatSender;